﻿// StatusForm.cs
//

using System;
using System.Diagnostics;
using System.Windows.Forms;
using Facebook.Desktop;
using Facebook.Service;

namespace MyStatus {

    public partial class StatusForm : Form {

        private const string _apiKey = "[Your API Key]";
        private const string _secret = "[Your Secret]";

        private FacebookService _fbService;
        private bool _loggingIn;

        public StatusForm() {
            InitializeComponent();
        }

        private void LoadStatus() {
            _nameLabel.Text = "Loading...";

            User user = _fbService.Users.GetUser(null, "name,status");
            if (user != null) {
                _nameLabel.Text = user.Name;

                _statusTextBox.Text = user.Status.Message;
                _dateLabel.Text = user.Status.UpdateDate.ToLocalTime().ToString("g");
            }

            bool canSetStatus = _fbService.Permissions.IsPermissionGranted(Permission.SetStatus);
            _permissionsLink.Visible = !canSetStatus;
            _updateButton.Enabled = canSetStatus;
            _statusTextBox.ReadOnly = !canSetStatus;
        }

        protected override void OnActivated(EventArgs e) {
            base.OnActivated(e);

            if ((_fbService == null) && (_loggingIn == false)) {
                _loggingIn = true;

                try {
                    FacebookClientSession fbSession = new FacebookClientSession(_apiKey, _secret);
                    if (fbSession.Initialize(this)) {
                        _fbService = new FacebookService(fbSession);
                        LoadStatus();
                    }
                }
                finally {
                    _loggingIn = false;
                }
            }
        }

        private void OnRefreshButtonClick(object sender, EventArgs e) {
            LoadStatus();
        }

        private void OnUpdateButtonClick(object sender, EventArgs e) {
            string text = _statusTextBox.Text.Trim();

            _fbService.Users.SetStatus(text, /* includesVerb */ true);
            LoadStatus();
        }

        private void OnPermissionsLinkClick(object sender, EventArgs e) {
            string permissionsUrl = String.Format("http://www.facebook.com/authorize.php?api_key={0}&v=1.0&ext_perm=status_update",
                                                  _apiKey);
            Process.Start(permissionsUrl);
        }
    }
}
